package com.android.fragmentdemo.defineviews
import android.content.Context
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.Matrix
import android.graphics.Paint
import android.util.AttributeSet
import android.util.Log
import android.view.View
import com.android.fragmentdemo.R

class FoldRotateImageView @JvmOverloads constructor(
    context: Context,
    attributeSet: AttributeSet? = null
) : View(context, attributeSet) {

    private val mShadowPaint by lazy {
        Paint().apply {
            isAntiAlias = true
        }
    }

    private val mMatrix by lazy {
        Matrix()
    }

    private val mBitmap = BitmapFactory.decodeResource(context.resources, R.drawable.p10)


    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        setMeasuredDimension(mBitmap.width, mBitmap.height)
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        Log.d(TAG,"measuredWidth:${measuredWidth};measuredHeight:${measuredHeight}")
        canvas.apply {
            //平移
            //mMatrix.setTranslate(measuredWidth / 2.0F, measuredHeight / 2.0F)
            //旋转
            //mMatrix.setRotate(45F, measuredWidth.toFloat(), measuredHeight.toFloat())
            //平移
            //mMatrix.preTranslate(-measuredWidth / 2F, -measuredHeight / 2F)
            //mMatrix.postTranslate(measuredWidth / 2F, measuredHeight / 2F)

            //setPolyToPoly---截取图片的某一部分显示
            val srcPoints = floatArrayOf(mBitmap.getWidth().toFloat() / 8, mBitmap.getHeight().toFloat() / 8, mBitmap.getWidth().toFloat() * 3 / 4, mBitmap.getHeight().toFloat() * 3 / 4)
            val dstPoints = floatArrayOf(0F, 0F, mBitmap.getWidth().toFloat(), mBitmap.getHeight().toFloat())
            mMatrix.setPolyToPoly(srcPoints, 0, dstPoints, 0, 2)

            drawBitmap(mBitmap, mMatrix, mShadowPaint)
        }
    }

    companion object {
        const val TAG = "FoldRotateImageView"
    }
}